/**
 * 检测文本是否包含有意义的内容
 * 排除只有空格、换行、标点符号等情况
 */
export function hasMeaningfulContent(text: string): boolean {
  if (!text) return false
  const meaningfulPattern = /[\p{L}\p{N}]/u
  return meaningfulPattern.test(text)
}

/**
 * 生成会话ID
 */
export function generateSessionId(): string {
  return Date.now().toString(36) + Math.random().toString(36).substring(2, 10)
}

/**
 * 生成唯一消息ID
 */
export function generateMessageId(): string {
  return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
}

/**
 * 格式化文件大小
 */
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 检查是否为有效的图片文件
 */
export function isValidImageFile(file: File): boolean {
  return file.type.startsWith('image/')
}

/**
 * 检查文件大小是否超过限制
 */
export function isFileSizeValid(file: File, maxSize: number): boolean {
  return file.size <= maxSize
}

/**
 * 提取文件名（不含扩展名）
 */
export function getFileNameWithoutExtension(filename: string): string {
  const lastDotIndex = filename.lastIndexOf('.')
  return lastDotIndex > 0 ? filename.substring(0, lastDotIndex) : filename
}

/**
 * 防抖函数
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout | null = null
  
  return function executedFunction(...args: Parameters<T>) {
    const later = () => {
      timeout = null
      func(...args)
    }
    
    if (timeout !== null) {
      clearTimeout(timeout)
    }
    
    timeout = setTimeout(later, wait)
  }
}

/**
 * 节流函数
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let inThrottle: boolean
  
  return function executedFunction(this: any, ...args: Parameters<T>) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

/**
 * 滚动到元素底部
 */
export function scrollToBottom(element: HTMLElement, smooth: boolean = true) {
  if (element) {
    element.scrollTo({
      top: element.scrollHeight,
      behavior: smooth ? 'smooth' : 'auto'
    })
  }
}

/**
 * 检查是否需要自动滚动（用户是否在底部附近）
 */
export function shouldAutoScroll(element: HTMLElement, threshold: number = 100): boolean {
  if (!element) return false
  
  const isNearBottom = element.scrollHeight - element.scrollTop - element.clientHeight < threshold
  return isNearBottom
}

/**
 * 安全地解析JSON
 */
export function safeParseJSON<T>(str: string): T | null {
  try {
    return JSON.parse(str)
  } catch {
    return null
  }
}

/**
 * 获取当前时间戳
 */
export function getCurrentTimestamp(): number {
  return Date.now()
}

/**
 * 延迟执行
 */
export function delay(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms))
}